package com.jstyle.jclifexd.activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.NestedScrollView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.jstyle.jclifexd.R;
import com.jstyle.jclifexd.fragment.BaseFragment;
import com.jstyle.jclifexd.fragment.HealthHistoryDayFragment;
import com.jstyle.jclifexd.fragment.HealthHistoryMonthFragment;
import com.jstyle.jclifexd.fragment.HealthHistoryWeekFragment;
import com.jstyle.jclifexd.fragment.HealthHistoryYearFragment;
import com.jstyle.jclifexd.utils.DateUtil;
import com.jstyle.jclifexd.utils.ScreenUtils;
import com.jstyle.jclifexd.utils.Utils;

import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class HealthHistoryActivity extends BaseActivity {

    @BindView(R.id.bt_goal_back)
    Button btGoalBack;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_share)
    ImageView ivShare;
    @BindView(R.id.rb_heart_day)
    RadioButton rbHeartDay;
    @BindView(R.id.rb_heart_week)
    RadioButton rbHeartWeek;
    @BindView(R.id.rb_heart_month)
    RadioButton rbHeartMonth;
    @BindView(R.id.rb_heart_year)
    RadioButton rbHeartYear;
    @BindView(R.id.rg_history)
    RadioGroup rgHistory;
    @BindView(R.id.bt_sleep_week_pre)
    ImageView btSleepWeekPre;
    @BindView(R.id.bt_sleep_week_date)
    Button btSleepWeekDate;
    @BindView(R.id.bt_sleep_week_next)
    ImageView btSleepWeekNext;
    @BindView(R.id.FrameLayout_health)
    FrameLayout FrameLayoutHealth;
    HealthHistoryDayFragment healthHistoryDayFragment;
    HealthHistoryWeekFragment healthHistoryWeekFragment;
    HealthHistoryMonthFragment healthHistoryMonthFragment;
    HealthHistoryYearFragment healthHistoryYearFragment;
    @BindView(R.id.ll_NestedScrollView)
    NestedScrollView llNestedScrollView;

    private FragmentManager fragmentManager;
    private final static int FRAGMENT_DAY = 0;
    private final static int FRAGMENT_WEEK = 1;
    private final static int FRAGMENT_Month = 2;
    private final static int FRAGMENT_Year = 4;
    private int DATA_TYPE = 0;
    public final static int DATA_HRV = 0;
    public final static int DATA_BLOOD = 1;
    public final static int DATA_PRESSURE = 2;

    public static final String KEY_DATA_TYPE = "DATA_TYPE";
    public static final String KEY_DATA_DATE = "DATA_DATE";
    private String thisMonth;
    private String[] monthDates;
    private String[] thisWeek;
    String queryDate;
    private int year;
    public int dateType = 0;
    public final static int dateDay = 0;
    public final static int dateWeek = 1;
    public final static int dateMonth = 2;
    public final static int dateYear = 3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_health_history);
        ButterKnife.bind(this);
        initData();
        init();
    }

    private void initData() {
        DATA_TYPE = getIntent().getIntExtra(KEY_DATA_TYPE, DATA_HRV);
        String date=getIntent().getStringExtra(KEY_DATA_DATE);
        queryDate = TextUtils.isEmpty(date)?DateUtil.getDefaultFormatTime(new Date()):date;
        Calendar calendar=Calendar.getInstance();

        thisMonth = DateUtil.getMonthString("", DateUtil.this_month);
        monthDates = DateUtil.getThisMonth();
        thisWeek = DateUtil.getTodayWeek(0);
        year = Calendar.getInstance().get(Calendar.YEAR);
    }

    private String getTextTitle() {
        String title = "HRV";
        switch (DATA_TYPE) {
            case DATA_HRV:
                title = "HRV";
                break;
            case DATA_BLOOD:
                title = getString(R.string.bp);
                break;
            case DATA_PRESSURE:
                title = getString(R.string.stress);
                break;
        }
        return title;
    }

    private void init() {
        fragmentManager = getSupportFragmentManager();
        startTransaction(FRAGMENT_DAY);
        btGoalBack.setText(getTextTitle());
        ScreenUtils.setTitleTypeface(btGoalBack);
        rgHistory.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_heart_day:
                        startTransaction(FRAGMENT_DAY);
                        break;
                    case R.id.rb_heart_week:
                        startTransaction(FRAGMENT_WEEK);
                        break;
                    case R.id.rb_heart_month:
                        startTransaction(FRAGMENT_Month);
                        break;
                    case R.id.rb_heart_year:
                        startTransaction(FRAGMENT_Year);
                        break;
                }
            }
        });
    }

    protected void startTransaction(int fragmentId) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        hideFragment(fragmentTransaction);
        String showDate = "";
        String startDate = "";
        String endDate = "";
        BaseFragment baseFragment = null;
        switch (fragmentId) {
            case FRAGMENT_DAY:
                if (healthHistoryDayFragment == null) {
                    healthHistoryDayFragment = HealthHistoryDayFragment.newInstance(DATA_TYPE,queryDate);
                    fragmentTransaction.add(R.id.FrameLayout_health, healthHistoryDayFragment);
                } else {
                    fragmentTransaction.show(healthHistoryDayFragment);
                }
                dateType = dateDay;
                showDate = queryDate;
                baseFragment = healthHistoryDayFragment;
                break;
            case FRAGMENT_WEEK:
                if (healthHistoryWeekFragment == null) {
                    healthHistoryWeekFragment = HealthHistoryWeekFragment.newInstance(DATA_TYPE);
                    fragmentTransaction.add(R.id.FrameLayout_health, healthHistoryWeekFragment);
                } else {
                    fragmentTransaction.show(healthHistoryWeekFragment);
                }
                dateType = dateWeek;
                showDate = thisWeek[0] + "-" + thisWeek[6];
                startDate = thisWeek[0];
                endDate = thisWeek[6];
                baseFragment = healthHistoryWeekFragment;
                break;
            case FRAGMENT_Month:
                if (healthHistoryMonthFragment == null) {
                    healthHistoryMonthFragment = HealthHistoryMonthFragment.newInstance(DATA_TYPE);
                    fragmentTransaction.add(R.id.FrameLayout_health, healthHistoryMonthFragment);
                } else {
                    fragmentTransaction.show(healthHistoryMonthFragment);
                }
                dateType = dateMonth;
                showDate = getShowDate(monthDates[0]);
                startDate = monthDates[0];
                endDate = monthDates[monthDates.length - 1];
                baseFragment = healthHistoryMonthFragment;
                break;
            case FRAGMENT_Year:
                if (healthHistoryYearFragment == null) {
                    healthHistoryYearFragment = HealthHistoryYearFragment.newInstance(DATA_TYPE);
                    fragmentTransaction.add(R.id.FrameLayout_health, healthHistoryYearFragment);
                } else {
                    fragmentTransaction.show(healthHistoryYearFragment);
                }
                dateType = dateYear;
                showDate = String.valueOf(year);
                startDate = showDate.substring(2, 4) + ".01.01";
                endDate = showDate.substring(2, 4) + ".12.31";
                baseFragment = healthHistoryYearFragment;
                break;
        }
        showDate(showDate, baseFragment);
        fragmentTransaction.commit();
    }

    private void showDate(String showDate, BaseFragment baseFragment) {

        Calendar calendar = Calendar.getInstance();
        switch (dateType) {
            case dateDay:
                String nowDateT = DateUtil.getDefaultFormatTime(new Date());
                btSleepWeekDate.setText(DateUtil.getShowDay(this, showDate));
                btSleepWeekNext.setEnabled(!queryDate.equals(nowDateT));

                break;
            case dateWeek:
                btSleepWeekDate.setText(DateUtil.getShowWeekDate(this, thisWeek[0]) + "-" + DateUtil.getShowWeekDate(this, thisWeek[6]));

                String nowDate = DateUtil.getDefaultFormatTime(new Date());
                btSleepWeekNext.setEnabled(true);
                for (int i = 0; i < thisWeek.length - 1; i++) {
                    if (thisWeek[i].equals(nowDate)) {
                        btSleepWeekNext.setEnabled(false);
                        break;
                    }
                }
                break;
            case dateMonth:
                String monthDate = DateUtil.getShowMonthDate(this, monthDates[0]);
                btSleepWeekDate.setText(monthDate.contains("мая")?monthDate.replace("мая","май"):monthDate);
                btSleepWeekNext.setEnabled(DateUtil.monthEnable(this, monthDate));
                break;
            case dateYear:
                btSleepWeekDate.setText(showDate);
                int thisYear = calendar.get(Calendar.YEAR);
                btSleepWeekNext.setEnabled(year != thisYear);
                break;
        }
        if (baseFragment != null && baseFragment.isAdded()) {
            baseFragment.updateDate(showDate, DATA_TYPE);
        }
    }

    private static final String TAG = "HealthHistoryActivity";

    private String getShowDate(String monthString) {
        Locale locale = getResources().getConfiguration().locale;
        String language = locale.getLanguage();
        long time = DateUtil.getDateLong(monthString);
        String format = "";

        format = "yyyy-MM";

        return DateUtil.getFormatTimeString(time, format);
    }

    private void hideFragment(FragmentTransaction fragmentTransaction) {
        hideFragment(healthHistoryWeekFragment, fragmentTransaction);
        hideFragment(healthHistoryDayFragment, fragmentTransaction);
        hideFragment(healthHistoryMonthFragment, fragmentTransaction);
        hideFragment(healthHistoryYearFragment, fragmentTransaction);

    }

    private void hideFragment(Fragment fragment, FragmentTransaction transaction) {
        if (fragment != null) {
            transaction.hide(fragment);
        }
    }

    @OnClick({R.id.iv_back, R.id.iv_share, R.id.bt_sleep_week_pre, R.id.bt_sleep_week_next})
    public void onViewClicked(View view) {

        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_share:
                if(Utils.isFastClick()){return;}
                share();
                break;
            case R.id.bt_sleep_week_pre:
                showPreDate();
                break;
            case R.id.bt_sleep_week_next:
                showNextDate();
                break;
        }
    }

    /**
     * 上周，月，年
     */
    private void showPreDate() {
        String showDate = "";
        btSleepWeekNext.setEnabled(true);
        BaseFragment baseFragment = null;
        switch (dateType) {
            case dateDay:
                queryDate = DateUtil.getYesterdayDateString(queryDate);
                baseFragment = healthHistoryDayFragment;
                showDate = queryDate;
                break;
            case dateWeek:
                thisWeek = DateUtil.getWeekString(thisWeek[0], DateUtil.lastWeek);
                showDate = thisWeek[0] + "-" + thisWeek[6];
                baseFragment = healthHistoryWeekFragment;
                break;
            case dateMonth:
                thisMonth = DateUtil.getMonthString(thisMonth, DateUtil.last_month);
                monthDates = DateUtil.getLastMonth(monthDates[0]);
                showDate = getShowDate(monthDates[0]);
                baseFragment = healthHistoryMonthFragment;
                break;
            case dateYear:
                year--;
                showDate = String.valueOf(year);
                baseFragment = healthHistoryYearFragment;
                break;
        }
        showDate(showDate, baseFragment);
    }

    private void showNextDate() {
        String showDate = "";
        BaseFragment baseFragment = null;
        Calendar calendar = Calendar.getInstance();
        switch (dateType) {
            case dateDay:
                String nowDateT = DateUtil.getDefaultFormatTime(new Date());
                btSleepWeekNext.setEnabled(!queryDate.equals(nowDateT));
                queryDate = DateUtil.getTomorrowDateString(queryDate);
                showDate = queryDate;
                baseFragment = healthHistoryDayFragment;
                break;
            case dateWeek:
                String nowDate = DateUtil.getDefaultFormatTime(new Date());
                btSleepWeekNext.setEnabled(true);
                for (int i = 0; i < thisWeek.length - 1; i++) {
                    if (thisWeek[i].equals(nowDate)) {
                        btSleepWeekNext.setEnabled(false);
                        return;
                    }
                }
                thisWeek = DateUtil.getWeekString(thisWeek[6], DateUtil.nextWeek);
                showDate = thisWeek[0] + "-" + thisWeek[6];
                baseFragment = healthHistoryWeekFragment;

                break;
            case dateMonth:

                thisMonth = DateUtil.getMonthString(thisMonth, DateUtil.next_month);
                monthDates = DateUtil.getNextMonth(monthDates[0]);
                showDate = getShowDate(monthDates[0]);
                baseFragment = healthHistoryMonthFragment;

                break;
            case dateYear:
                int thisYear = calendar.get(Calendar.YEAR);
                btSleepWeekNext.setEnabled(year != thisYear);
                if (thisYear == year) return;
                year++;
                showDate = String.valueOf(year);
                baseFragment = healthHistoryYearFragment;
                break;
        }
        showDate(showDate, baseFragment);
    }

    private void share() {
        ScreenUtils.shareFile(this,llNestedScrollView);
    }
}
